import { login, logout, getInfo } from '@/api/login'
import router, { suffixRouterMap } from '@/router/index'

const Layout = () => import('@/views/Layout.vue')

const user = {
  state: {
    user: {
      token: '',
      username: '',
      avatar: '',
      roles: []
    },
    menu: []
  },

  getters: {
    token: state => state.user.token,
    avatar: state => state.user.avatar,
    username: state => state.user.username,
    roles: state => state.user.roles,
    menu: state => state.menu,
    defaultOpens: state => {
      if (state.menu && state.menu.length > 0) {
        const arr = []
        arr.push('' + state.menu[0].menuId)
        return arr
      }
    }
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.user.token = token
    },
    SET_NAME: (state, name) => {
      state.user.username = name
    },
    SET_AVATAR: (state, avatar) => {
      state.user.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.user.roles = roles
    },
    SET_ROUTERS: (state, routers) => {
      state.routers = routers
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
    }
  },

  actions: {
    // 登录
    Login({ commit }, user) {
      return new Promise((resolve, reject) => {
        login(user.username, user.password)
          .then(response => {
            commit('SET_TOKEN', response.token)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.user.token)
          .then(response => {
            const data = response.data
            // 设置全局用户相关状态数据
            commit('SET_ROLES', data.roles)
            commit('SET_NAME', data.name)
            commit('SET_AVATAR', data.avatar)
            commit('SET_MENU', data.menu)

            // 根据菜单动态生成异步路由
            let accessedRouters = generateRoutesFromMenu(data.menu, [])
            let finalRouters = accessedRouters.concat(suffixRouterMap)
            console.log(finalRouters)
            // vue2.2.2 新增动态路由添加方式
            router.addRoutes(finalRouters)
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            // clear all vuex state
            commit('SET_AVATAR', '')
            commit('SET_NAME', '')
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 前端登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        resolve()
      })
    }
  }
}

/**
 * 递归生成和menu对应的路由用于动态添加到路由表
 * vue2.2的addRoute方法如果route重复name会有warning，目前没有解决办法，不过不影响使用
 * @param asyncRouterMap
 * @param roles
 */
function generateRoutesFromMenu(menu = [], routes = []) {
  for (let i = 0, l = menu.length; i < l; i++) {
    let item = menu[i]
    if (item.list === null && item.component) {
      // 对每一个带有component属性的菜单添加路由
      let route = {
        path: '/',
        name: '首页',
        component: Layout,
        children: [
          {
            path: item.url,
            name: item.name,
            component: resolve =>
              require(['@/views/' + item.component + '.vue'], resolve)
          }
        ]
      }
      routes.push(route)
    }
    if (item.list !== null) {
      item.component = generateRoutesFromMenu(item.list, routes)
    }
  }
  return routes
}

export default user
